package com.example.usermanagement.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordUtils {
    /**
     * MD5加密（加盐更安全，此处先简化，后续可扩展）
     * @param password 原始密码
     * @return 32位MD5加密后的密码
     */
    public static String md5Encrypt(String password) {
        if (password == null || password.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                int num = b & 0xFF; // 转为无符号整数
                String hex = Integer.toHexString(num);
                if (hex.length() == 1) {
                    sb.append("0"); // 补零，确保32位
                }
                sb.append(hex);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            // 转为运行时异常，避免业务层捕获
            throw new RuntimeException("MD5加密失败：" + e.getMessage(), e);
        }
    }
}